package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQuery;
import cn.wolfcode.crm.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        //先删除关系
        employeeMapper.deleteRelation(id);
        //再删除员工的数据
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        //在账户信息保存前将密码加密后再保存（用户名做盐）
        String password = employee.getPassword();
        Md5Hash md5Hash = new Md5Hash(password, employee.getName());
        System.out.println(md5Hash.toString());
        //设置加密的结果
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);//插入员工，再插入关系
        //判断传过来的 ids 数组是否为空
        if (ids != null && ids.length > 0) {
            //不为空时，保存时就要连关系一起保存
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //从中间表中删除原有的关系数据
        employeeMapper.deleteRelation(employee.getId());
        //再从中间表中存入新的的关系数据
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    /**
     * 登录业务的权限判断
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public Employee login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new RuntimeException("账户和密码不存在！");
        }
        return employee;
    }

    @Override
    public PageInfo query(EmployeeQuery qo) {
        //开启分页
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());

        //查询结果集
        List<Employee> list = employeeMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void batchDelete(Long[] ids) {
        //方式1：循环调用delete方法删除，效率低
        //方式2：SQL的foreach
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    /**
     * 创建Excel文件，用于导出文件
     *
     * @return
     */
    @Override
    public Workbook exportXls() {
        //创建Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet（一页纸）
        Sheet sheet = wb.createSheet("员工名单");


        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);

            //创建行
            Row row = sheet.createRow(i + 1);
            //单元格
            //Cell cell = row.createCell(0);
            //设置内容到单元格中
            //cell.setCellValue("Hello!");
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());

        }

        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws Exception {
        //把接收到的文件以Excel的方式去读取并操作
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页：索引指定位置
        HSSFSheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引值
        int lastRowNum = sheet.getLastRowNum();
        //循环页面，一行一行的读
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            HSSFRow row = sheet.getRow(i);
            if (row != null) {
                //将一行数据中的对应单元格的值设置到对象的属性中
                Employee employee = new Employee();
                employee.setName(row.getCell(0).getStringCellValue());
                employee.setEmail(row.getCell(1).getStringCellValue());
                //单元格的内容格式是文本时的处理方式
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
                //单元格的内容格式是数值时的处理方式(Double要转成int)
                //employee.setAge((int) row.getCell(2).getNumericCellValue());
                //调用保存的方法，将对象保存
                this.save(employee, null);
            }else{
                return;
            }
        }

    }


}
